using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ZeroconfService;

namespace SmokeAlarm
{
	public partial class Browser : Form
	{
		NetServiceBrowser nsBrowser = new NetServiceBrowser();
		bool mBrowsing = false;

		public Browser(DummyForm dummyForm)
		{
			InitializeComponent();

			m_dummyForm = dummyForm;
			nsBrowser.InvokeableObject = this;
			nsBrowser.DidFindService += new NetServiceBrowser.ServiceFound(nsBrowser_DidFindService);
			nsBrowser.DidRemoveService += new NetServiceBrowser.ServiceRemoved(nsBrowser_DidRemoveService);
		}

		void nsBrowser_DidRemoveService(NetServiceBrowser browser, NetService service, bool moreComing)
		{
			servicesList.BeginUpdate();

			foreach (ListViewItem item in servicesList.Items)
			{
				if (item.Tag == service)
					servicesList.Items.Remove(item);
			}

			servicesList.EndUpdate();
		}

		ArrayList waitingAdd = new ArrayList();
		void nsBrowser_DidFindService(NetServiceBrowser browser, NetService service, bool moreComing)
		{
			ListViewItem item = new ListViewItem(service.Name);
			item.Tag = service;

			if (moreComing)
			{
				waitingAdd.Add(item);
			}
			else
			{
				servicesList.BeginUpdate();
				while (waitingAdd.Count > 0)
				{
					servicesList.Items.Add((ListViewItem)waitingAdd[0]);
					waitingAdd.RemoveAt(0);
				}
				servicesList.Items.Add(item);
				servicesList.EndUpdate();
			}
		}

		public void StartBrowsing()
		{
			if (!mBrowsing)
			{
				string service = "_smoketp._tcp.";

				nsBrowser.SearchForService(service, "local.");

				mBrowsing = true;
			}
		}

		void resolve_DidResolveService(NetService service)
		{

		}

		void resolve_DidUpdateTXT(NetService service)
		{

		}

		private void servicesList_SelectedIndexChanged(object sender, EventArgs e)
		{
			NetService selected = null;
			try
			{
				selected = (NetService)servicesList.SelectedItems[0].Tag;
			}
			catch (Exception)
			{
				selected = null;
			}

			if (selected != null)
			{
				m_dummyForm.Resolve(selected);
			}
		}

		private DummyForm m_dummyForm;
	}
}